package com.ken.mymongodb.xmldb;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import com.google.gson.Gson;
import com.ken.work.util.StringUtil;

public class MyDBUtil {

	private static String dbPath = null;
	/**
	 * 启动时，加载数据文件路径
	 */
	static {
		ClassLoader classLoader = Thread.currentThread()
				.getContextClassLoader();
		dbPath = classLoader.getResource("").toString()
				.replaceFirst("file:/", "");
		System.out.println("数据库文件路径："+dbPath);
	}

	/**
	 * 创建数据库
	 * 
	 * @throws Exception
	 */
	public void createDb(String dataBaseName) throws Exception {
		if (!StringUtil.isNotEmpty(dataBaseName))
			throw new NullPointerException("the database name cannot be empty");
		Document doc = new Document();
		Element database = new Element("database").setAttribute("name",
				dataBaseName);
		doc.setRootElement(database);
		Element table_indexs = new Element("table");
		database.addContent(table_indexs.setAttribute("name", "system.indexs"));
		Element table_users = new Element("table");
		database.addContent(table_users.setAttribute("name", "system.users"));
		// 把创建的xml文档写到流中
		Format format = Format.getCompactFormat();
		format.setEncoding("UTF-8");
		format.setIndent("	");
		XMLOutputter out = new XMLOutputter(format);

		out.output(doc, new FileOutputStream(dbPath + dataBaseName + ".xml"));
	}
/**
 * 创建数据表
 * @param 数据库名称
 * @param 表名
 * @throws JDOMException
 * @throws IOException
 */
	public void createTable(String dataBase,String table) throws JDOMException, IOException{
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(new File(dbPath + dataBase + ".xml"));
		Element rootEle=doc.getRootElement();
		if(dataBase.equals(rootEle.getAttributeValue("name")))
		{
			Iterator itr = (rootEle.getChildren()).iterator();
			while(itr.hasNext()) {
			     Element oneLevelDeep = (Element)itr.next();
			     if("table".equals(oneLevelDeep.getName())&&table.equals(oneLevelDeep.getAttributeValue("name")))
			     {
			    	 throw new JDOMException("the table already exists");
			     }		     
		   }
			//create
			Element newElement=new Element("table");
			newElement.setAttribute("name", table);
			rootEle.addContent(newElement);
			Format format = Format.getCompactFormat();
			format.setEncoding("UTF-8");
			format.setIndent("	");
			XMLOutputter out = new XMLOutputter(format);
			out.output(doc, new FileOutputStream(dbPath + dataBase + ".xml"));

		}else {
			throw new JDOMException("no such node");
		}
		
	}
	/**
	 * 
	 * 插入数据
	 * @param 数据库名称
	 * @param 表名
	 * @param 插入对象
	 * @throws JDOMException
	 * @throws IOException
	 */
	public void insert(String dataBase,String table,Object obj) throws JDOMException, IOException{
		Gson gson = new Gson();
		String json = gson.toJson(obj);
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(new File(dbPath + dataBase + ".xml"));
		Element rootEle=doc.getRootElement();
		boolean flag=false;
		if(dataBase.equals(rootEle.getAttributeValue("name")))
		{
			Iterator itr = (rootEle.getChildren()).iterator();
			while(itr.hasNext()) {
			     Element oneLevelDeep = (Element)itr.next();
			     if("table".equals(oneLevelDeep.getName())&&table.equals(oneLevelDeep.getAttributeValue("name")))
			     {
			    	 flag=true;
			    	Element newElement=new Element("data");
			    	String idStr=UUID.randomUUID().toString();
					newElement.setAttribute("id", idStr);
					Map mp=gson.fromJson(json, Map.class);
					mp.put("_id", idStr);
					json = gson.toJson(mp);
					newElement.addContent(json);
					oneLevelDeep.addContent(newElement);
					Format format = Format.getCompactFormat();
					format.setEncoding("UTF-8");
					format.setIndent("	");
					XMLOutputter out = new XMLOutputter(format);
					out.output(doc, new FileOutputStream(dbPath + dataBase + ".xml"));
					 break;
			     }	
			      
		   }
			if(flag==false)
				throw new JDOMException("no such table");
			//create
			

		}else {
			throw new JDOMException("no such database");
		}
		 
	}
	/**
	 * 修改数据库
	 * 
	 * @param 数据库名称
	 * @param 表名
	 * @param 要操作的id
	 * @param 修改对象
	 * @throws JDOMException
	 * @throws IOException
	 */
	public void update(String dataBase,String table,String id,Object obj) throws JDOMException, IOException{
		Gson gson = new Gson();
		String json = gson.toJson(obj);
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(new File(dbPath + dataBase + ".xml"));
		Element rootEle=doc.getRootElement();
		boolean flag=false;
		if(dataBase.equals(rootEle.getAttributeValue("name")))
		{
			Iterator itr = (rootEle.getChildren()).iterator();
			while(itr.hasNext()) {
			     Element oneLevelDeep = (Element)itr.next();
			     if("table".equals(oneLevelDeep.getName())&&table.equals(oneLevelDeep.getAttributeValue("name")))
			     {
			    	Iterator itr2 = (oneLevelDeep.getChildren()).iterator();
					while(itr2.hasNext()) {
						Element dataLevelDeep = (Element)itr2.next();
						if("data".equals(dataLevelDeep.getName())&&id.equals(dataLevelDeep.getAttributeValue("id")))
					     {
							flag=true;
							dataLevelDeep.removeContent();

							Map mp=gson.fromJson(json, Map.class);
							mp.put("_id", id);
							json = gson.toJson(mp);
							dataLevelDeep.addContent(json);
							 
							Format format = Format.getCompactFormat();
							format.setEncoding("UTF-8");
							format.setIndent("	");
							XMLOutputter out = new XMLOutputter(format);
							out.output(doc, new FileOutputStream(dbPath + dataBase + ".xml"));
							break;
					     }
					}
			     }			      
		   }
			if(flag==false)
				throw new JDOMException("no such data");
			//create
		}else {
			throw new JDOMException("no such database");
		}	 
	}
	/**
	 * 查询所有的数据
	 * @param 数据库名称
	 * @param 表名
	 * @return List<Map>
	 * @throws JDOMException
	 * @throws IOException
	 */
	public List<Map> loadDatas(String dataBase,String table) throws JDOMException, IOException{
		List<Map> allmap=new ArrayList<Map>();
		Gson gson = new Gson();
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(new File(dbPath + dataBase + ".xml"));
		Element rootEle=doc.getRootElement();
		boolean flag=false;
		if(dataBase.equals(rootEle.getAttributeValue("name")))
		{
			Iterator itr = (rootEle.getChildren()).iterator();
			while(itr.hasNext()) {
			     Element oneLevelDeep = (Element)itr.next();
			     if("table".equals(oneLevelDeep.getName())&&table.equals(oneLevelDeep.getAttributeValue("name")))
			     {
			    	 flag=true;
			    	Iterator itr2 = (oneLevelDeep.getChildren()).iterator();
					while(itr2.hasNext()) {
						
						Element dataLevelDeep = (Element)itr2.next();
						String valStr=dataLevelDeep.getText();
						System.out.println(valStr);
						Map mp = gson.fromJson(valStr, Map.class);
						allmap.add(mp);
					}
			     }			      
		   }
			if(flag==false)
				throw new JDOMException("no such data");
			//create
		}else {
			throw new JDOMException("no such database");
		}
		return allmap;
	} 
}
